package org.wyn.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.wyn.common.ResultType;
import org.wyn.mongodb.bean.User;
import org.wyn.service.ILoginService;

import com.google.inject.Inject;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 登录action
 * @author wyn
 *
 */
@Namespace("/login")
@ParentPackage("unSecurity")
public class LoginAction extends WynActionSupport {
	
	/**
	 * 输入跳转
	 */
	@Action(value="input",results = {@Result(name = INPUT, type = ResultType.FREEMARKER, location = "login_input.ftl")})
	public String input(){
		return INPUT;
	}
	
	/**
	 * 登录
	 * @return
	 */
	@Action(value="login",results = {
			@Result(name = INPUT, type = ResultType.FREEMARKER, location = "login_input.ftl")
			,@Result(name = SUCCESS, type = ResultType.REDIRECT, location = "../index/index")
			})
	public String login(){
		User user = iLoginService.login(userName, password);
		if(user != null){//登录成功
			HttpServletRequest request = ServletActionContext.getRequest(); 
			HttpSession session = request.getSession();
			session.setAttribute("user", user);//用户信息保存在session中
			return SUCCESS;
		}else{//登录失败，用户密码错误
			return INPUT;
		}
	}
	/**
	 * 登出,登出后回到登录页面
	 * @return
	 */
	@Action(value="logout",results = {
			@Result(name = SUCCESS, type = ResultType.PLAIN_TEXT)
			})
	public String logout(){
		HttpServletRequest request = ServletActionContext.getRequest();
		//将session中保存的用户相关信息清空，即登出
		request.getSession().setAttribute("user", null);
		output("true");
		return SUCCESS;
	}
	@Inject
	private ILoginService iLoginService;
	private String userName;
	private String password;
	
	private static final long serialVersionUID = 1L;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public ILoginService getiLoginService() {
		return iLoginService;
	}

	public void setiLoginService(ILoginService iLoginService) {
		this.iLoginService = iLoginService;
	}

}
